<template>
  <div>用户名：{{ nickName }}</div>
  <div>openId: {{ openId }}</div>
  <div>{{ JSON.stringify(userInfo) }}</div>
  <h5>用户信息</h5>
  <div class="avatar"><img :src="userInfo.headimgurl" alt=""></div>
  <div>昵称：{{ userInfo.nickName }}</div>
  <div>昵称：{{ userInfo.openid }}</div>
  <div>性别：{{ userInfo.sex === 0 ? '男' : '女' }}</div>
  <div>国家：{{ userInfo.country }}</div>
  <div>城市：{{ userInfo.city }}</div>
  <div>省份：{{ userInfo.province }}</div>
  
  <button @click="getPageRedirect">授权</button>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute} from 'vue-router'
import axios from 'axios'

const route = useRoute()
onMounted(() => {
  const { code } = route.query
  if (code) {
    getOpenId(code)
  }
})
// 重定向
const getPageRedirect = async () => {
  const url = window.location.href.split('?')[0]
  const res = await axios.get(`/wechat/redirect?url=${url}`)
  location.href = res.data
}
// 获取openid
const openId = ref('')
const accessToken = ref('')
const getOpenId = async (code) => {
  const res = await axios.get(`/wechat/getOpenId?code=${code}`)
  if (res && res.data) {
    const { openid, access_token } = res.data
    openId.value = openid
    accessToken.value = access_token
    getUserInfo()
  }
}
// 获取用户信息
const userInfo = ref({})
const getUserInfo = async () => {
  const { data } = await axios.get('/wechat/getUserInfo')
  if (data) {
    userInfo.value = data.data
    nickName.value = data.data.nickName
  }
}

const nickName = ref('111')
</script>

<style scoped>
.avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  margin: 20px auto;
}
</style>